"""
@Time    : 11/9/18 2:28 PM
@Author  : chengyue_he
"""

import six
import ujson
from flask import jsonify


class ErrorCodeField(int):
    def __new__(cls, error_code, message=u""):
        obj = int.__new__(cls, error_code)
        obj.message = message
        return obj


class ErrorCodeMetaClass(type):
    def __new__(cls, name, bases, namespace):
        code_message_map = {}
        for k, v in namespace.items():
            if getattr(v, '__class__', None) and isinstance(v, ErrorCodeField):
                if code_message_map.get(v):
                    raise ValueError("duplicated codde {0} {1}".format(k, v))
                code_message_map[v] = getattr(v, 'message', "")
        namespace["CODE_MESSAGE_MAP"] = code_message_map
        return type.__new__(cls, name, bases, namespace)


class BaseErrorCode(six.with_metaclass(ErrorCodeMetaClass)):
    CODE_MESSAGE_MAP = NotImplemented
    SUCCESS = ErrorCodeField(0, u'ok')

    @staticmethod
    def to_json(statuscode, result=None):
        """json序列化结果"""
        '''
        response = {
                "trackId": "",  # 对应的用户
                "error_code": "0",  # 如果正确，则为0，如果错误，则为具体错误值
                "error_desc": "",  # 如果error_code为0，则为空，为非0，则有错误描述
                "data": {

                }# 根据具体协议，返回不同的值
            }
        '''
        if result is None:
            dict_result = {
                "error_code": statuscode,
                "error_status":"失败",
                "error_msg": statuscode.message,
                "data":"",
            }
        else:
            dict_result = {
                "error_code": statuscode,
                "error_status": "成功",
                "error_msg": statuscode.message,
                "data": {"result":result}
            }
        return ujson.dumps(dict_result, ensure_ascii=False)


class System(BaseErrorCode):
    """ 系统服务错误 """
    SERVICE_UNAVAILABLE = ErrorCodeField(10001, u"服务器内部错误!")


class User(BaseErrorCode):
    """ user 服务接口错误码 """
    '''
    错误代码：
    失败（请求错误code=4001）、
    失败（查询崩溃code=4002）、
    失败（系统故障code=4003）、
    后续还有其他具体的错误再继续加
    '''
    PARAMETER = ErrorCodeField(4001, u'请求错误')
    SEARCH = ErrorCodeField(4002, u'ES查询崩溃')
    SYSTEM = ErrorCodeField(4003, u'系统故障')
    # NUMERROR = ErrorCodeField(20004, u'超过处理数据，处理数量限制在10000内，请检查后重新尝试')
